package by.grsu.vashchilo.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


import by.grsu.vashchilo.entity.Trip;
import by.grsu.vashchilo.table.TripTable;
import by.grsu.vashchilo.dao.impl.AbstractDao;




public class TripDao extends AbstractDao<TripTable, Trip>{

	public TripDao(String rootFolderPath) {
		super(rootFolderPath);
	}

	public Trip searchById(Long desiredTrip) {
		final TripTable tripTable = deserializeFromXml();
		Trip trip = new Trip();
		for (final Trip c : tripTable.getRows()) {
			if (c.getID().equals(desiredTrip)) {
				trip = c;
				break;
			}
		}
		return trip;
	}

	@Override
	public void saveNew(final Trip newTrip) {
		newTrip.setId(getNextId());
		final TripTable tripTable = deserializeFromXml();
		tripTable.getRows().add(newTrip);
		serializeToXml(tripTable);
	}

	@Override
	public void update(final Trip entity) {
		final TripTable tripTable = deserializeFromXml();
		for (final Trip c : tripTable.getRows()) {
			if (c.getId().equals(entity.getId())) {
				c.setID(entity.getID());
				c.setWhere(entity.getWhere());
				c.setTimeOfDeparture(entity.getTimeOfDeparture());
				c.setPrice(entity.getPrice());
				break;
			}
		}
		serializeToXml(tripTable);

	}

	@Override
	public Trip get(Serializable id) {
		final TripTable tripTable = deserializeFromXml();
		for (final Trip c : tripTable.getRows()) {
			if (c.getId().equals(id)) {
				return c;
			}
		}

		return null;
	}

	@Override
	public List<Trip> getAll() {
		final TripTable tripTable = deserializeFromXml();
		return tripTable.getRows();
	}
	public List<Long> getAllID() {
		final TripTable tripTable = deserializeFromXml();
		List<Long> listID= new ArrayList();
		for (Trip c : tripTable.getRows()) {
			listID.add(c.getId());
		}
		return listID;
	}


	@Override
	public void delete(Serializable id) {
		final TripTable tripTable = deserializeFromXml();
		Trip toBeDeletedTrip = null;
		for (final Trip c : tripTable.getRows()) {
			if (c.getId().equals(id)) {
				toBeDeletedTrip = c;
				break;
			}
		}
		tripTable.getRows().remove(toBeDeletedTrip);
		serializeToXml(tripTable);
	}

	@Override
	protected Class<TripTable> getTableClass() {
		return TripTable.class;
	}
}
